<?php

namespace App\Http\Controllers\Attendance;

use App\Http\Controllers\Controller;
use App\Models\Attendance\AttendanceData;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use App\Models\Dict;

class AttendanceDataController extends Controller
{
    public function attendanceList(Request $request)
    {
        $params = $request->all();

        if (isset($params['date'])) {
            $params['date'] = date('Y-m-d', strtotime($params['date']));
        } else {
            $params['date'] = date('Y-m-d');
        }
        $data = $this->getAttendanceList($params)
            ->orderBy('date', 'desc')
            ->get()
            ->toArray();
        $result = [
            'attendanceRecord' => $data,
            'date' => $params['date'],
            'busNumber' => isset($params['busNumber']) ? $params['busNumber'] : '',
            'name' => isset($params['name']) ? $params['name'] : '',
            'line' => isset($params['line']) ? $params['line'] : '-1',
            'type' => isset($params['type']) ? $params['type'] : '-1',
        ];
        return response()->formatJson($result);
    }
    /**
     * 拼接查询sql
     *
     * @param [array] $params
     * @return Builder
     */
    public function getAttendanceList($params): Builder
    {
        $query = AttendanceData::query();

        if (isset($params['busNumber'])) {
            $query->where('busNumber', 'like', '%' . $params['busNumber'] . '%');
        }

        if (isset($params['name'])) {
            $query->where('name', 'like', '%' . $params['name'] . '%');
        }

        if (isset($params['line']) && '-1' != $params['line']) {
            $query->where('line', $params['line']);
        }

        if (isset($params['type']) && '-1' != $params['type']) {
            $query->where('type', $params['type']);
        }

        $query->whereDate('date', $params['date']);

        return $query;
    }

    /**
     * 创建车队长上报信息记录
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function storeAttendance(Request $request)
    {
        $params = $request->all();
        $message = '';
        //处理日期
        if ($params['date']) {
            $params['date'] = date('Y-m-d', strtotime($params['date']));
        } else {
            $message .= '请选择日期';
        }
        //处理车牌号
        if ($params['busNumber']) {
            $params['busNumber'] = str_replace('陕G', '', $params['busNumber']);
            //处理上报的车牌号,将其中字母转化为大写
            $params['busNumber'] = strtoupper($params['busNumber']);
        } else {
            $message .= '请填写车牌号';
        }
        //处理驾驶员名称
        if ($params['name']) {
            $params['name'] = str_replace(' ', '', $params['name']);
        } else {
            $message .= '请填写驾驶员名称';
        }
        //处理类型
        if (!$params['type']) {
            $message .= '请选择上报类型';
        }
        switch (mb_substr($params['type'], 0, 2)) {
            case '半天':
                $params['duration'] = '0.5';
                break;
            case '全天':
                $params['duration'] = '1';
                break;
            default:
                $params['duration'] = '1';
                break;
        }
        //处理线路
        if ($params['line']) {
            $params['line'] = str_replace('路', '', $params['line']);
        } else {
            //获取当前查询月份车辆线路分布
            $params['line'] = DB::table('akbus_bus_distribution')
                ->where('license_plate_num','like', $params['busNumber'].'%')
                ->where('date', '<=', $params['date'])
                ->where('end_date', '>=', $params['date'])
                ->value('line');
        }
        $result = '';
        if (!$message) {
            //核对是否已经添加此条信息
            $id = DB::table('akbus_attendance_data')->where($params)->value('id');
            if ($id) {
                $message .= '已经添加过相同的数据信息,请仔细核对';
            } else {
                //判断是否需要同步考勤汇总的数据
                if ($params['date'] < date('Y-m-d')) {
                    //上报数据不是当天的,需要汇总
                    $updateData = [];
                    switch ($params['type']) {
                        case '半天修车':
                            $updateData['fixTime'] = 0.5;
                            break;
                        case '半天请假':
                            $updateData['leaveTime'] = 0.5;
                            break;
                        case '半天停运':
                            $updateData['stopTime'] = 0.5;
                            break;
                        case '半天检气瓶':
                            $updateData['checkGas'] = 0.5;
                            break;
                        case '全天修车':
                            $updateData['fixTime'] = 1;
                            break;
                        case '全天请假':
                            $updateData['leaveTime'] = 1;
                            break;
                        case '全天停运':
                            $updateData['stopTime'] = 1;
                            break;
                        case '全天检气瓶':
                            $updateData['checkGas'] = 1;
                            break;
                        default:
                            break;
                    };
                    $this->harmonizeCollect($updateData, $params);
                }
                $charteredCar = new AttendanceData($params);
                $result = $charteredCar->save();
                $message = $result ? '添加成功' : '添加失败';
            }
        }
        return response()->formatJson($result, $message);
    }
    /**
     * 同步车队长上报数据到考勤汇总
     *
     * @param  $updateData 修改的数据
     * @param  $params
     * @return void
     */
    public function harmonizeCollect($updateData, $params)
    {

        $bus_collect_id = DB::table('akbus_bus_attendance_collect')
            ->where('signDate', $params['date'])
            ->where('busNumber', $params['busNumber'])
            ->where('is_del', 0)
            ->value('id');
        if ($bus_collect_id) {
            //有相应数据进行修改
            DB::table('akbus_bus_attendance_collect')
                ->where('id', $bus_collect_id)
                ->update($updateData);
        } else {
            //无相应数据判断是否添加
            if ($params['busNumber'] != '无' && $params['busNumber'] != '') {
                $busInsertData = $updateData;
                $busInsertData['signDate'] = $params['date'];
                $busInsertData['busNumber'] = $params['busNumber'];
                $busInsertData['line'] = $params['line'];
                $busInsertData['created_at'] = date('Y-m-d H:i:s');
                DB::table('akbus_bus_attendance_collect')->insert($busInsertData);
            }
        }
        $driver_collect_id = DB::table('akbus_driver_attendance_collect')
            ->where('signDate', $params['date'])
            ->where('driver', $params['name'])
            ->where('is_del', 0)
            ->value('id');
        if ($driver_collect_id) {
            DB::table('akbus_driver_attendance_collect')
                ->where('id', $driver_collect_id)
                ->update($updateData);
        } else {
            //无相应数据判断是否添加
            if ($params['name'] != '无' && $params['name'] != '') {
                $driverInsertData = $updateData;
                $driverInsertData['signDate'] = $params['date'];
                $driverInsertData['driver'] = $params['name'];
                $driverInsertData['line'] = $params['line'];
                $driverInsertData['created_at'] = date('Y-m-d H:i:s');
                DB::table('akbus_driver_attendance_collect')->insert($driverInsertData);
            }
        }
    }

    /**
     * 删除车队长上报信息记录
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroyAttendance(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            foreach ($ids as  $id) {
                $attendanceData = AttendanceData::query()->find($id)->toArray();
                if ($attendanceData['date'] < date('Y-m-d')) {
                    //需要同步考勤汇总记录
                    //处理类型
                    $updateData = [];
                    switch ($attendanceData['type']) {
                        case '半天修车':
                        case '全天修车':
                            $updateData['fixTime'] = 0;
                            break;
                        case '半天请假':
                        case '全天请假':
                            $updateData['leaveTime'] = 0;
                            break;
                        case '半天停运':
                        case '全天停运':
                            $updateData['stopTime'] = 0;
                            break;
                        case '半天检气瓶':
                        case '全天检气瓶':
                            $updateData['checkGas'] = 0;
                            break;
                        default:
                            break;
                    }
                    $this->harmonizeCollect($updateData, $attendanceData);
                }
            }
            $delCount = AttendanceData::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }
    /**
     * 获取车队长上报类型
     *
     * @return void
     */
    public function getReportType()
    {
        $data = Dict::getOptionsByName('车队长上报类型');
        $result = [];
        foreach ($data as $k => $v) {
            $result[$k]['label'] = $v['title'];
            $result[$k]['value'] = $v['value'];
        }
        return response()->formatJson($result);
    }
}
